

/**
 * _getMapper 获取映射的UI对象
 * 
 * @return {Object} 映射的UI对象
 */
function _getMapper(ctr) {
	var mapper = ctr.data('mapper');
	return mapper || null;
}
 
/**
 * _getMapper UI对象的映射对象
 * 
 * @return {JQDom} UI对象
 */
function _setMapper(ctr, mapper) {
	return ctr.data('mapper', mapper);
}

/**
 * ccaySetValue 设置录入对象的值
 * 
 * @param {Boolean}
 *            value 值
 * @return {JQDom} 对象本身
 */
$.fn.ccaySetValue = function(value) {
	if (!Ccay.DataHelper.hasValue(value))
		value = "";
	var mapper = _getMapper(this);
	if (mapper && mapper.setValue)
		mapper.setValue(value, this);
	else
		// this.val(value);
		this.manager().setValue(value);

	return this;
}
/**
 * ccayGetValue 读取录入对象的值
 * 
 * @return value
 */
$.fn.ccayGetValue = function() {
	var mapper = _getMapper(this);
	if (mapper && mapper.getValue)
		return mapper.getValue();
	else
		// return this.val();
		return this.manager().getValue().trim();
}

/**
 * ccayReset form对象重置方法
 * 
 * @return value
 */
$.fn.ccayReset = function() {
	this.find("input[type='hidden']").val("");
	this[0].reset();
	var validator = this.data("validator");
	if(validator && validator.reset){
		validator.reset(); 
		validator.resetForm();
	}
	this.find("input.ccay-dropdown,textarea.ccay-dropdown").each(function() { 
				$(this).ccaySetValue(this.value);
			});
	this.find(".ccay-user").each(function() {
				$(this).ccaySetValue("");
			});
	this.find(".error-ctr").removeClass("error error-ctr");
	this.find("label.error").hide();
	return this;
}

/**
 * ccayDisabled 设置对象是否可用
 * 
 * @param {Boolean}
 *            enabled 是否可用
 * @return {JQDom} 对象本身
 */
$.fn.ccayDisabled = function(enabled) {
	var mapper = _getMapper(this);
	if (mapper && mapper.setEnabled)
		enabled ? mapper.setEnabled() : mapper.setDisabled();
	else {
		this.manager().disabled(enabled);
	}
}

/**
 * ccayDatepicker 初始化日期控件
 * 
 * @param {String}
 *            format 可选（默认系统配置格式),默认为：'date'；日期时间：'datetime'
 * @return {JQDom} 对象本身
 */
$.fn.ccayDatepicker = function(format) {
	return this.calendar(format);
}
/** @description hasPermission权限标签 渲染接口 */
$.fn.ccayHasPermission = function() {
	return this.each(function() {
				// 得到标签上标注的权限点
				var checkCtr = $(this), permissionExpression = checkCtr.attr("ccayPermission") || "";
				Ccay.Permission.check(permissionExpression) ? checkCtr.show() : checkCtr.remove()
			})
}
/** @description noPermission权限标签 渲染接口 */
$.fn.ccayNoPermission = function() {
	return this.each(function() {
				// 得到标签上标注的权限点
				var checkCtr = $(this), permissionExpression = checkCtr.attr("ccayPermission") || "";
				Ccay.Permission.check(permissionExpression, "noPermission") ? checkCtr.show() : checkCtr.remove()
			})
}

/**
 * @description 渲染国际化标签接口
 */
$.fn.ccayI18n = function() {
	return this.each(function() {
				var ctr = $(this), key = $.trim(ctr.attr("i18nKey")), value = $.i18n.prop(key);

				if (!key || key == value) {
					var innerValue = ctr.attr(workspaceVO.currentLanguage);
					if (innerValue) {
						value = innerValue;
					}
				}

				if (ctr.prop("tagName") === "INPUT") {
					ctr.val(value);
					return;
				}

				var i18nFor = ctr.attr("i18nfor");

				if (!i18nFor)
					ctr.text(value);
				else
					ctr.attr(i18nFor, value);
			})
}

/**
 * 
 * @param {}
 *            datas 需要遍历的tree型数据结构
 * @param {}
 *            childField 子字段名称，不传默认为children
 * @param {}
 *            fn
 */
$.nodeEach = function(datas, childField, fn) {
	if (!datas)
		return;
	childField = childField || "children";
	if ($.isArray(datas)) {
		for (var i = 0, node; node = datas[i]; i++) {
			$.nodeEach(node, childField, fn)
		}
	} else if (datas[childField]) {
		fn.call(datas);
		$.nodeEach(datas[childField], childField, fn)
	} else {
		fn.call(datas)
	}
}
$.nodeQuery = function(data,childField, queryField,fieldValue) { 
	var result = null;
	$.nodeEach(data,childField,function(){
		if(this && this[queryField] === fieldValue){
			result =  this;
			return false;
		}
	})
	return result;
} 

/**
 * @function Ccay.load(url, [callback] )
 * @descriptoion 基于jqeury的load的方法，载入远程资源页面后，做一些渲染操作
 * @param {String}
 *            url一个包含发送请求的URL字符串,或以注册的资源key值
 * @param {Function}
 *            callback 载入成功后的回调
 */
$.fn.ccayLoad = function(url, callback, noscroll, erorCallback) {
	var moduleName = url;
	this.empty().html("");
	// 清除久的module，更新module
	var module = this.attr('module');
	var closeDialog = module ? Ccay.Core.Namespace.register(module).closeDialog : "";
	var context = module ? Ccay.Core.Namespace.register(module).context : "";
	if (module) {
		Ccay.Module.remove(module);
		closeDialog && (Ccay.Core.Namespace.register(module).closeDialog = closeDialog);
		context && (Ccay.Core.Namespace.register(module).context = context);
	}
	this.attr('module', url);
	if (Ccay.Permission.res && Ccay.Permission.res.get(url.split("?")[0])) {
		Ccay.UI.loadingClose();
		map = new Ccay.HashMap();
		Ccay.doGet("services/ccay/registry/query/list/{0}/{1}".formatURI("Ccay.Security.NoPermissionMsg", false), '', function(data) {
					for (var a = 0; a < data.length; a++) {
						map.put(data[a].name, data[a].value);
					}
					// 配置是否启用优化后的无权限提示页面
					if (map.get("MessageType") == 1) {
						// add by zWX304259/5.4.17 对url格式为:xxx?param=xxx做转义处理,否则会丢失param=xxx
						Ccay.Page.forward("ccay/security/noPermission/noPermissionMessage.html?paramUrl=" + encodeURIComponent(url));
					} else {
						Ccay.UI.showMessage("ccay.common.message.noPrivilegeError", "error");
					}
				});
		return;
	}
	var me = this;
	this.load(Ccay.Page.register(url), null, function(responseText, textStatus, xhr) {
				if (textStatus == "error") {
					erorCallback && erorCallback();
					// 处理错误
					Ccay.UI.loadingClose(true);
					var loadObject = {
						target : me,
						url : url,
						callback : callback
					}
					Ccay.Component.handleError(responseText, textStatus, xhr, reloadResource, loadObject);
				} else {
					Ccay.Page.afterLoad(me);
					if (typeof callback === "function") {
						callback();
					}
					var m = Ccay.Core.Namespace.get(moduleName);
					// 如果是非dialog模块，则跳到页面顶部，或者noscroll参数不为true，则默认跳到页头
					if (!(m && m.closeDialog) && !noscroll) {
						window.scroll(0, 0);
						$('#hidFocus').focus();
					}
					var helperPanel = me.parent(".ccay-dialog");
					helperPanel = helperPanel.length > 0 ? helperPanel : me;
					Ccay.Component.Helper && Ccay.Component.Helper.showHelper(Ccay.Page.register(url), helperPanel);
					Ccay.Component.InfoTip && Ccay.Component.InfoTip.init(Ccay.Page.register(url));
				}
			});
}

/**
 * @description 初始化inputHistory标签 $("input:text")
 * 
 */
$.fn.ccayInputHistory = function(){
	var input = $(this)
	var id=input.id(),index=0,valueText='valueText';
	if (!id) {
		id = 'listoryInput_' + (index++) + '';
		input.id(id);
	}
	try{
		var arr = [];
		input.attr('init',true);
		//
		Ccay.UI.delayEvent(input,'blur',function(){
			var localStorageValue = JSON.parse(Ccay.LocalStorage.getItem(valueText));
			if(input.val()!==""){
	          if(localStorageValue===null){
	        	  Ccay.LocalStorage.setItem(valueText,JSON.stringify([$(this).val()]));
				}else{
					var newDate =[];
					
					for(var i=0;i<localStorageValue.length;i++){
						if(input.val()!=localStorageValue[i]){
							newDate.push(localStorageValue[i]);
						}
					}
					//ratio(newDate,data)
					if(newDate.length==localStorageValue.length){
						newDate.push(input.val());
						Ccay.LocalStorage.setItem(valueText,JSON.stringify(newDate));
					}
				}
			
			}
		});
		
		input.keydown(checkInput.keydown);
		Ccay.UI.delayEvent2(input, 'keyup',function(e){
			var keyCode = e.keyCode;
			if(keyCode!=40&&keyCode!=38&&keyCode!=13&&keyCode!=9){
				var data = JSON.parse(Ccay.LocalStorage.getItem(valueText)),input = $(this).val(),newDate = [];
				//checkInput.ratio(newDate,data,$(this))
				
				$('.selectorList').remove();
				if(this.val()==""&&data!=null){
					if($('.selectorList').length==0){
						checkInput.buildStyle(this,data.splice(0,100));
					}
				}
				else if(this.val()!=""&&data!=null){
						var aResult = [];
						for(var i =0;i<data.length;i++){
							datas = findLocal(input,data[i]);
							if(datas>=0){
								aResult[aResult.length] = data[i];
							}
						}
						checkInput.buildStyle(this,aResult);
						if($('.selectorList ul li').length==0){
							$('.selectorList').remove();
						}
				}
			}
		});
		Ccay.UI.delayEvent(input,'click',function(e){
			var data = JSON.parse(Ccay.LocalStorage.getItem(valueText))
			if(input.val()==""&&data!=null){
				$('.selectorList').remove();
				if($('.selectorList').length==0){
					checkInput.buildStyle(input,data.splice(0,100));
				}
			}
			e.stopPropagation();
		});
		
		$(document).bind('click',function(){
			$('.selectorList').hide();
		})
	}catch(e){
		
	}
	
}

var checkInput = {
		buildStyle:function(input,data){
			var ccaySelector = $.create('div','ccay-selector selectorList'),panelBegin ="<ul class='list'>",panelEnd="</ul>";
			var id=input.id();
			id += '_ddl1';
			ccaySelector.id(id);
			ccaySelector.appendTo(Ccay.UI.getPopupPanel());
			$.create('div','ccay-selector-body').appendTo(ccaySelector);
			
			var body = ccaySelector.children('.ccay-selector-body');
			body.html(panelBegin + panelEnd);
			
			for(var i=0;i<data.length;i++){
				$('<li class="list-item" ><span class="list-text">'+(data[i]+"").encode()+'</span></li>').appendTo(ccaySelector.find('.list'));
			}
			body.find('.list-item:first').addClass('selected-pre');
			if(input.isVisiable()){
				var position = {};
				position.top = (position.top||0)+input.outerHeight();
				ccaySelector.show();
				Ccay.UI.popup(input,ccaySelector,position,null,true,null,true);
				checkInput.setWidth(ccaySelector,input,body);
				ccaySelector.delegate('.list-item',"click",function(e){
					var text = $($(this).find('.list-text').get(0)).text();
				    if(text == void 0){
				    	text = '';
				    }
				    input.val(text);
				    input.focus();
				    ccaySelector.hide();
				    e.stopPropagation();
				});
			}
			
		},
		
		setWidth :function(selector,input,body){
			var child = selector.find('.list');
			if(child.length){
				childWidth=child.width(),
				inputWidth=input.outerWidth(),
				minWidth = inputWidth;
				var width = Ccay.DataHelper.getRangeValue(childWidth, minWidth, 0);
				if (child.height() > selector.height()){
				//当有滚动条效果时，预留滚动条宽度
					if(childWidth > inputWidth - 17){
				selector.width(width + 17);
						child.width(width);
					} else{
						 selector.width(width);
						 child.width(width- 17);
					}
				}
				else{
				selector.width(width);
			if (width > childWidth)
				child.width(width);
				}
			}
			
			var height = child.outerHeight();
			if(height && child.width() > body.width())
				height += 20;
			body.height(height || "auto");
		},
		keydown:function(e){
			var selector = $('.ccay-selector'),input = $(this),selectPre = 'selected-pre',len = $('.selectorList').length;
			if(selector.length){
				var keyCode = e.keyCode;
				if(keyCode==38||keyCode==40 && len){
					var currentItem = selector.find('.'+selectPre), selectedItem;
					if (currentItem.length == 0) {
						selectedItem = selector.find('.' + op.itemClass+ ':visible:'+ (e.keyCode == 38 ? 'last' : 'first'));
					} else {
						currentItem.removeClass(selectPre);
						if (keyCode == 38) {
							selectedItem = currentItem.prevAll(':visible:first');
							if (selectedItem.length == 0)
								selectedItem = selector.find('.' + op.itemClass + ':visible:last');
						} else {
							selectedItem = currentItem.nextAll(':visible:first');
							if (selectedItem.length == 0)
								selectedItem = selector.find('.' + op.itemClass + ':visible:first');
						}
					}
					if(selectedItem.length){
						selectedItem.addClass(selectPre);
						//处理滚动条效果
						var top = selectedItem.position().top,body = selector.find('.ccay-selector-body');
						if(top){
							var height = selectedItem.outerHeight() + top - body.height();
							height && body.scrollTop(height + body.scrollTop() + 100);
						}
						else
							body.scrollTop(0);
					}
				}else if (keyCode == 13 || keyCode == 9) {
					//回车事件和tab事件
					if(keyCode === 13){
						//dropdown.clearInterval(op);
					}
					keyCode != 9 && e.stopPropagation();
					var op = selector.data('op'),
						item = selector.find(':not(.hide).' + selectPre + ':first');
					
					if (len && item.length && keyCode == 13) {
						var text,value;
						text = $(item.find('.list-text').get(0)).text();
						if(text == void 0)
							text='';
						input.val(text);
						selector.hide();
						}
					
					} else {
						if(input.validVal().length || keyCode == 9){
							if (!input.data("called")){
								input.data('called',1);
							}
						}
						
					}
			}
		}
}

function findLocal(value,text){
	var valueSize =value.length,textSize = text.length,compare;
	if(valueSize<=textSize){
		for(var i=0;i<=textSize-valueSize+1;i++){
			compare = text.substring(i,i+valueSize);
			if(compare == value){
				return i;
			}
		}
	}
	return -1;
}

/**
 * 会话重建后的回调函数
 * 
 * @param loadObject
 */
function reloadResource(loadObject) {
	loadObject.target.ccayLoad(loadObject.url, loadObject.callback);
}

/**
 * 树形菜单设置高亮
 * 
 * @param tree
 * @param filterValue
 */
function setHighShow(tree,manager){
	if(!manager)return;
	var filterValue = manager.setting.filterDataValue;
	if(!filterValue){
		//清除高亮
		tree.find("li span font").each(function(){
			$(this).replaceWith($(this).text());
		});
		return;
	}
	
	var setting = manager.setting;
	//设置高亮
	tree.find("li span").each(function(){
		if(/<.*>/g.test($(this).text())){
			return;
		}
		var highText = $(this).text();
		try{
			var reg = new RegExp(filterValue.toLowerCase(),"gi");
			highText = highText.replace(reg,function(value){
				return "<font style='background:"+(setting.highShowBackGround||"yellow")+";color:"+(setting.highShowColor||"inherit")+";'>"+value+"</font>";
			});
			$(this).html(highText);
		}catch(ex){
			
		}
	});
}

/**
 * 树控件
 * 
 * @param {Object}
 *            dataOrUrl 数据或数据服务地址
 * @param {Object}
 *            options 参数配置expandLevel,checkType,
 *            showRemoveBtn:false,onCheck:null,onDblClick:null,onClick:null,onRemove:null
 * @param {function}
 *            callback 回调方法
 * @return {JqDom} 当前dom对象
 */
$.fn.ccayTree = function(dataOrUrl, options, callback) {
	options = options || {};
	if(!$(options.filter).is("input")){
		$("#filter_" + this.prop("id")).remove();// 清空过滤器
	}
	var tree, me = this.empty().addClass("ztree");
	options.data = options.data || {};
	var setting = {
		highShow:options.highShow,//是否高亮，默认高亮
		highShowBackGround:options.highShowBackGround,//高亮背景色
		highShowColor:options.highShowColor,//高亮字体颜色
		expandByCount : options.expandByCount || 1000,//展开所有的长度，长度太大会消耗性能
		expandLevel : options.expandLevel,// 自动展开节点级别
		selectItems : options.selectItems,// 多选tree，根据该值回选
		selectField : options.selectField,// 多选tree，根据该字段回选
		view : {
			showLine : false
		},
		callback : {
			// 用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作
			beforeDrag : function(treeId, treeNodes) {
				if (!options.onDrop) {// 设置可拖拽是开启
					return false;
				} else {
					options.onDrag && options.onDrag(treeId, treeNodes)
				}
			},
			// 用于捕获节点被拖拽之前的事件回调函数，并且根据返回值确定是否允许开启拖拽操作,(treeId, treeNodes, targetNode, moveType)
			beforeDrop : options.beforeDrop,
			// 用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作,，默认不可拖拽
			onDrop : function(event, treeId, treeNodes, targetNode, moveType) {
				if (options.onDrop) {
					options.onDrop(event, treeId, treeNodes, targetNode, moveType);
				} else {
					return false;
				}
			},
			// 用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
			beforeRemove : function(treeId, treeNode) {
				options.onRemove && options.onRemove(treeId, treeNode);
				return false;
			},
			// 用于捕获节点编辑名称结束,(treeId, treeNode, newName),返回false阻止重命名
			// Input 失去焦点 或 按下 Enter 键之后，更新节点名称数据之前的事件回调函数，
			beforeRename : options.beforeRename,
			// 用于捕获节点编辑名称结束之后的事件回调函数。(event, treeId, treeNode)
			onRename : options.onRename,
			// 用于捕获 zTree 上鼠标单击之后的事件回调函数,(event, treeId, treeNode)
			onClick : function(event, treeId, treeNode) {
				// 点击勾选事件
				if(options.click2Check){
					var check = treeNode.checked ? false : true;
					$("#" + treeId).getCcayTreeManager().checkNode(treeNode, check, options.checkboxType);
				};
				options.onClick && options.onClick(event, treeId, treeNode);
			},
			// 用于捕获 zTree 上鼠标双击之后的事件回调函数,(event, treeId, treeNode)
			onDblClick : options.onDblClick,
			// 用于勾选前的事件，返回false阻止勾选，(treeId, treeNode)
			beforeCheck :  options.beforeCheck,
			// 用于捕获 checkbox / radio 被勾选 或 取消勾选的事件回调函数,(event, treeId, treeNode)
			onCheck : options.onCheck,
			// 用于捕获父节点收缩之前的事件函数，并且根据返回值确定是否允许收缩操作，参数(treeId, treeNode)，返回布尔值
			beforeCollapse :  options.beforeCollapse,
			// 用于捕获节点被收缩的事件回调函数,参数(event, treeId, treeNode)
			onCollapse : options.onCollapse,
			// 用于捕获父节点展开之前的事件回调函数，并且根据返回值确定是否允许展开操作，(treeId, treeNode)
			beforeExpand : options.beforeExpand,
			// 用于捕获节点被展开的事件回调函数，(event, treeId, treeNode)
			onExpand : function(event, treeId, treeNode){
				options.highShow!==false && setHighShow($("#"+treeNode.tId),$("#"+treeId).getCcayTreeManager());
				options.onExpand && options.onExpand(event, treeId, treeNode);
			}
		},
		edit : {
			enable : true,
			showRenameBtn : options.showRenameBtn || false,
			showRemoveBtn : options.showRemoveBtn || false,
			removeTitle : "Remove"
		},
		data : {
			key : options.key || {
				checked : options.checked || "checked",
				name : options.displayName || "name",
				title : options.title,
				children : options.children || "children"
			},
			simpleData : options.simpleData
		},
		view : {
			expandSpeed : "",
			// 自定义节点操作按钮
			addHoverDom : function(treeId, treeNode) {
				options.addHoverDom && options.addHoverDom(treeId, treeNode);
			},
			// 移除自定义节点操作按钮
			removeHoverDom : function(treeId, treeNode) {
				options.removeHoverDom && options.removeHoverDom(treeId, treeNode);
			},
			//节点文本是否可选
			txtSelectedEnable: options.txtSelectedEnable
		},
		check : {
			enable : options.checkType || false,
			chkStyle : options.checkType == "single" ? "radio" : "checkbox",
			chkboxType : options.checkboxType || {
				"Y" : "p",
				"N" : "s"
			},
			radioType : "all"
		}
	}
	setting.data.key = options.data.key || setting.data.key;
	// 如果允许节点url模式跳转，则关闭编辑
	if (options.urlMode) {
		setting.edit.enable = false;
	}
	if (setting.data.simpleData) {
		setting.data.simpleData.enable = true;
	}
	if (typeof dataOrUrl == "string") {
		/\{0\}/g.test(dataOrUrl) && (setting.filterDataByParameter = true);
		setting.treeFilterData = function(filterValue,isCall){
			Ccay.UI.ajax({
					url : dataOrUrl.formatURI(filterValue),
					loading : 'ui',
					success : function(data) {
						// 根据keepParent 与 回选参数 （selectField,selectItems） 处理数据
						if (options.chkDisableds || options.keepParent || setting.selectField && options.selectItems) {
							$.nodeEach(data, options.children, function() {
										if (setting.selectField && ($.isArray(setting.selectItems) ? setting.selectItems.contains(this[setting.selectField]) : options.selectItems == this[setting.selectField])) {
											this[setting.data.key.checked] = true;
										}
										if (options.keepParent) {
											this.isParent = true
										}

										if (options.chkDisableds && options.chkDisableds.contains(this[options.selectField])) {
											this.chkDisabled = true;
											$.nodeEach(this, options.children, function() {
														this.chkDisabled = true;
													})
										}
									});
						}
						setting.filterDataLength = ($.isArray(data) ? data : [data]).length;
						tree = $.fn.zTree.init(me, setting, $.isArray(data) ? data : [data]);
						_setMapper(me, tree);

						if (setting.expandLevel || setting.expandLevel === 0) {
							for (var i = 0; i <= parseInt(setting.expandLevel); i++)
								me.find("li.level" + i).each(function() {
											tree.expandNode(tree.getNodeByTId(this.id), true, null, false);
										});
						}
						
						//选中节点
						if(setting.check.chkStyle == "radio" && setting.selectItems){
							tree.selectNode(tree.getNodeByParam(setting.data.key.checked,true));
						}
						if(!isCall)return;
						Ccay.Core.log('before call');
						(typeof callback == "function") && callback(data);
						data = callback = null;
					}
				}, me.parent());
		};
		setting.treeFilterData(options.filterDataValue||"",true);
		// Ccay.doGet(dataOrUrl, "", )

	} else if (typeof dataOrUrl == "object") {
		var data = dataOrUrl;
		// 根据keepParent 与 回选参数 （selectField,selectItems） 处理数据
		if (options.chkDisableds || options.keepParent || setting.selectField && options.selectItems) {
			$.nodeEach(data, options.children, function() {
						if (setting.selectField && ($.isArray(setting.selectItems) ? setting.selectItems.contains(this[setting.selectField]) : options.selectItems == this[setting.selectField])) {
							this[setting.data.key.checked] = true;
						}
						if (options.keepParent) {
							this.isParent = true
						}
						if (options.chkDisableds && options.chkDisableds.contains(this[options.selectField])) {
							this.chkDisabled = true;
							$.nodeEach(this, options.children, function() {
										this.chkDisabled = true;
									})
						}
					});
		}
		setting.filterDataLength = data.length;
		tree = $.fn.zTree.init(me, setting, data);
		_setMapper(me, tree);
		if (setting.expandLevel) {
			for (var i = 0; i <= parseInt(setting.expandLevel); i++)
				me.find("li.level" + i).each(function() {
							tree.expandNode(tree.getNodeByTId(this.id), true, null, false);
						});
		}
		
		//选中节点
		if(setting.check.chkStyle == "radio" && setting.selectItems){
			tree.selectNode(tree.getNodeByParam(setting.data.key.checked,true));
		}
		
		(typeof callback == "function") && callback(data);
		data = callback = null;
	}

	// 过滤器逻辑
	if (options.filter) {
		var input;
		if($(options.filter).is("input")){
			input = $(options.filter);
		}else{
			var inptDiv = $('<div id="filter_' + this.prop("id") + '" class="ccay-tree-filter" ><input type="text" style="width:100%" maxlength="100" /></div>');
			inptDiv.insertBefore(this);
			input = inptDiv.find("input");
		}
		input.attr("search", "");
		var fn;
		var filterClear = $('<a href="javascript:;" class="ccay-tree-filter-clear">×</a>');
		input.after(filterClear);
		filterClear.click(function(){
			input.val("").focus();
			fn.call(input);
		});
		Ccay.UI.delayEvent2(input, "keyup", fn = function() {
					var tree = this.parent().parent().find(".ztree");
					var filterValue = this.val().trim();
					filterValue ? filterClear.show() : filterClear.hide();
					input.attr("search", filterValue.toLowerCase())
					Ccay.UI.treeFilter(tree, filterValue, options.showFilterChildren);
					if(tree.id() == "leftSiteMapTree"){
						Ccay.Layout.refreshScroller();
					}
				}, 500, function() {
					return input.attr("search") != input.val().trim().toLowerCase();
				})

		input.bind("paste", function(e) {
					setTimeout(function() {
								fn.call(input)
							}, 20)
		 });
		 
		 if('placeholder' in document.createElement('input')){ 
			input.attr("placeholder",$i18n("ccay.home.label.filter"));
		}else{
			input.addClass("filter-gray").val($i18n("ccay.home.label.filter")).focus(function(){ 
				if(this.value == $i18n("ccay.home.label.filter")){
					$(this).val("").removeClass("filter-gray");
				}
			}).focusout(function(){
				if(!this.value.trim()){
					$(this).addClass("filter-gray").val($i18n("ccay.home.label.filter"))
				}
			});
		}	
	}
	return this;
}
/**
 * 得到树管理器，该管理器对象包含一系列的api，可存取数据，或操作树的动作
 * 
 * @return {object} treeManager
 */
$.fn.getCcayTreeManager = function() {
	var tree = _getMapper(this);
	return tree;
}
/**
 * Tree过滤器实现方法
 * 
 * @param {}
 *            inpt
 */

Ccay.UI.treeFilter = function(tree, filterValue, showFilterChildren,selectNode) {
	tree.children("li.nomatchresult").remove();
	tree.removeClass("nobottom");
	if(filterValue === $i18n("ccay.home.label.filter")){
		filterValue = "";
	}
	var manager = tree.getCcayTreeManager();
	if(!manager) return ;
	if(manager.setting && manager.setting.filterDataByParameter){
		manager.setting.treeFilterData(filterValue);
		return;
	}
	manager.setting.filterDataValue = filterValue.toLowerCase();
	tree.find("style[id^='hideCss_']").remove();
	if (!filterValue) {
		(tree.attr("id")=="leftSiteMapTree" || manager.setting.filterDataLength<manager.setting.expandByCount) && manager.expandAll(false);
		manager.setting.highShow!==false && setHighShow(tree,tree.getCcayTreeManager());
		if (manager.getSelectedNodes().length > 0 && selectNode!==false) {
			setTimeout(function() {
				var activeElement = document.activeElement;
				manager.selectNode(manager.getSelectedNodes()[0], true);
				activeElement.focus();
			}, 500)
		}
		return;
	}
	filterValue = filterValue.toLowerCase();
	var attr = manager.setting.data.key.name;
	var allNodes = manager.getNodes();
	var hideCss = new Array();
	function filter(parentNode,childrenNodes,isParentHas) {
		if(isParentHas){
			return 0;
		}
		var filterCount = 0;
		$.each(childrenNodes,function(i,_node){
			var filterIndex = _node[attr].toLowerCase().indexOf(filterValue),parentHas=false;
			if (filterIndex>-1) {
				parentHas = true;
				filterCount++;
			}
			if (!_node.children && filterIndex == -1 && !parentHas) {
				hideCss.push("#"+_node.tId);
			}
			if(_node.children){
				filterCount += filter(_node,_node.children,parentHas);
			}
		});
		if(!parentNode){
			return filterCount;
		}
		if(parentNode[attr].toLowerCase().indexOf(filterValue)>-1){
			filterCount++;
		}
		if(!filterCount){
			hideCss.push("#"+parentNode.tId);
		}
		return filterCount;
	}	
	// 调用过滤器实现
	filter(null,allNodes);
	(tree.attr("id")=="leftSiteMapTree" || manager.setting.filterDataLength<manager.setting.expandByCount) && manager.expandAll(true);
	manager.setting.highShow!==false && setHighShow(tree,tree.getCcayTreeManager());
	var hideCssIndex = 0;
	while(hideCss.length){
		var cssString = "<style id='hideCss_"+tree.attr("id")+"'>"+hideCss.splice(0,1000).join(",")+"{display:none !important;}"+"</style>";
		tree.append(cssString);
		hideCssIndex++;
	}
	if(!tree.children("li:not(.nomatchresult):visible").length){
		tree.addClass("nobottom");
		$('<li class="nomatchresult"></li>').text($i18n("ccay.common.tree.noMatch")).appendTo(tree);
	}
}

/**
 * @description 显示loading
 */
$.fn.loading = function(isGlobal, isPop, position) {
	var loadingPanel = isGlobal ? $(document.body) : this;
	var loading = loadingPanel.children('div.loading');

	var width = this.outerWidth(), height = this.outerHeight();
	if (loading.length == 0) {
		loading = $(document.createElement('div')).addClass('loading').appendTo(loadingPanel);
		isGlobal && loading.id("globalloading");
	}
 
	if (!position) {

		if (isPop == void 0 && this.parents('div.ccay-dialog:first,div.ccay-igrid-editpanel,div.gt-editor-container:first,div.ccay-selector:first,.ccay-popup:first').length > 0) {
			isPop = true;
		}

		position = isPop ? this.position() : this.offset();

		if (!isGlobal && (width < 50 || height < 50)) {
			if (width < 30 || height < 30)
				loading.addClass('loading_min');
			else
				loading.addClass('loading_small');
		}
	}

	loading.css({
				width : width,
				height : height || '',
				top : position && position.top > 0 ? position.top : 0,
				left : position && position.left > 0 ? position.left : 0
			}).show();

	return this;
}
/**
 * @description 显示关闭loading
 */
$.fn.loadingClose = function() {
	var loading = this.children('div.loading');
	if (loading.length == 0)
		loading = $('#globalloading');

	loading.length && loading.remove();
	return this;
}

// -------------------------------- UserInfo
// --------------------------------------
/**
 * @description 初始化UserInfo标签 $(".PersonInfoEng,.PersonInfo,.PersonInfoChn")
 * @return {JqDom} 对象本身
 */
$.fn.ccayUserInfo = function() {
	this.each(function(index, tag) {
				var me = $(this);
				me.attr("href", "#");
				var data = me.data("w_user_info");
				if (!data) {
					me.click(function() {
								Ccay.Component.popUserInfo(me.attr("title") || me.text(), me.attr("url"));
								return false;
							});
					me.data("w_user_info", true);
				}
			});
}
/**
 * @description 初始化UserInfo标签 $(".PersonInfoEng,.PersonInfo,.PersonInfoChn")
 * @return {JqDom} 对象本身
 */
$.fn.ccayGroupInfo = function() {

	this.each(function(index, tag) {
				var me = $(this);
				me.attr("href", "#");
				var data = me.data("w_group_info");
				if (!data) {
					me.click(function() {
								Ccay.Component.popGroupInfo(me.attr("title") || me.text());
								return false;
							});
					me.data("w_group_info", true);
				}
			});
}
/**
 * @description 验证初始化
 * @return {JqDom} 对象本身
 */
$.fn.ccayValidate = function(op) {
	if (!op)
		op = {};

	this.removeData("validator");

	var validtor, errNum = 0;

	if (!op.errorPlacement)
		op.errorPlacement = function(error, ctr,isWarning) {
			if (error.text()) {
				errNum++;
				Ccay.UI.toggleValid(false, ctr, error, false, op, errNum,isWarning);
			}
		};
	if (!op.success)
		op.success = function(error) {
			Ccay.UI.toggleValid(true, error.prev(), error, false, op);
		}

	validtor = this.bind("invalid-form.validate", function() {
				// if(op.summaryError && validtor.errorList.length)
				// {
				// var sumError=[];
				// $.each(validtor.errorList,function(i,n){
				// sumError.push("<b>[" + n.element.name+"]</b>" + n.message);
				// });
				// Ccay.UI.showMessage("<ul
				// class='ccay-valid-sumerror'><li>"+sumError.join("</li><li>")
				// + "</li></ul>",'warn');
				// }
				errNum = 0;
			}).validate(op);

	return this;
}
Ccay.UI.toggleValid = function(result, ctr, errorLbl, isServerError, op, errNum,isWarning) {
	if (result) {
		if (errorLbl.length > 0) {
			ctr.removeClass('error');
			errorLbl.remove();
		}
	} else {
		if (ctr.length == 0) {
			Ccay.UI.showMessage(errorLbl.text(), 'warn');
		} else {
			// ctr.isVisiable() ||
			// Ccay.UI.Validator.check(ctr.parents(".ccay-hideValid"));
			if (errNum > 1) {
				ctr.isVisiable() || Ccay.UI.Validator.check(ctr.parents(".ccay-hideValid"));
			} else if (errNum == 1) {
				setTimeout(function() {
						if(!ctr.isVisiable())
						{
							Ccay.UI.Validator.check(ctr.parents(".ccay-hideValid"));
							ctr.valid();
						}
							// ctr.focus();
							var top = ctr.offset().top - 30, docEL = document.documentElement;
							if (top < (docEL.scrollTop || document.body.scrollTop)) {
								window.scrollTo(null, top < docEL.clientHeight ? 0 : top - 100);
							}
						}, 500);
			}
			if(isWarning)
				return;
			var position = ctr.position(), width = ctr.outerWidth();

			if(ctr.is(":visible")){
				
				errorLbl.addClass('error').css({
							top : position.top,
							left : position.left + width + 5
						}).click(function() {
							$(this).hide().addClass('er-handle');
						}); 
	
				isServerError && errorLbl.addClass('er-server');
				ctr.addClass('error-ctr').after(errorLbl);
				
				var popup_div = ctr.parents(".ccay-popup"),
					igrid_body = ctr.parents(".ccay-igrid-body:first"),
					label_top = position.top,
					label_left = position.left + width + 5;
					
				if(popup_div.length && popup_div.hasClass("ccay-dialog")){
					var popup_div_body = popup_div.manager().getBody(),
						popup_div_top =  popup_div_body.scrollTop() ;
					label_top += popup_div_top ? popup_div_top : 0;
				}else if(igrid_body.length){
					label_top += igrid_body.scrollTop();
				}
				
				var relative =  errorLbl.show().offsetParent();
				if(relative.length > 0 && errorLbl.position().left + errorLbl.width() > relative.width() ||
					relative.length == 0 && errorLbl.position().left + errorLbl.width() > screen.width || ctr.attr("errorInfoBottom")
				){
				  	label_top += ctr.height() + 5;
				  	label_left = position.left + 1;
				}
				
				errorLbl.css({left:label_left,top:label_top});
				
			}else{
				ctr.addClass('error-ctr')
			}
			 
		}
	}
}
Ccay.UI.Validator = {
	modes : [{
		css : 'l-tab-content-item',
		check : function(target) {
			var tabID = target.attr('tabid');
			if (tabID) {
				var tab = target.parents('.ccay-tab:first').getCcayTabManager();
				tab && tab.selectItem(tabID);
			}
		}
	}],
	check : function(target) {
		if (target.length) {
			var handler = target.attr('validHandler');
			if (handler) {
				handler = Ccay.DataHelper.getObj(handler);
				handler && handler(target);
			} else {
				var isInner;
				$.each(this.modes, function(i, n) {
							if (n.css && target.hasClass(n.css)) {
								n.check && n.check(target);
								isInner = true;
								return false;
							}
						});
				isInner || target.show();
			}
		}
	}
}

/**
 * 页面弹出框接口,调用方式如
 * Ccay.UI.dialog("xx/xx/test1.html","我的弹出框"，{width:320,height:200})
 * 
 * @param {String}
 *            url 弹出页路径或路径key值
 * @param {String}
 *            title 弹出框标题
 * @param {Object}
 *            options 可省略，其他常用参数如下、 {Number} width： dialog显示宽度， 默认为 280 {Number}
 *            height，diaolog显示高度，默认为自适应高度 {boolean} modal：是否为模式窗口， 默认为true
 *            {boolean} load ： 页面载入方式 默认为true，填写false为iframe方式载入 {Object}
 *            buttons: 按钮设置，如
 *            buttons:[{text:"确定",onclick:function(item,dialog){alert("ok")},{text:'取消',onclick:
 *            function (item, dialog) { dialog.close();}}]
 */
Ccay.UI.dialog = function(url, title, options) {
	//debugger;
	// 若只传了两个参数，第二参数则处理为options 
	// added by l00195395 in 2013-6-5
	if(typeof title == "object"){
		options = title;
		title = $i18n("ccay.common.label.select");
	};
	options = options || {};
	options.width = options.width || 480;
	options.fnLoad = options.fnLoad || options.callback;
	options.fnBeforeClose = options.fnBeforeClose || options.beforeClose;
	var moduleObj = false;
	if (url && Ccay.Page.has(url)) {
		moduleObj = Ccay.Core.Namespace.register(url);
	}
	options.fnDestory = function() {
		Ccay.Module.remove(url);
	}
	$("#ccayContentPanel").css("visibility", "inherit");
	var dlg = $().dialog($.extend({
				url : url,
				title : title
			}, options));
	dlg.close = function() {
		dlg.find(".ccay-dialog-closeimg").click();
	};

	if (moduleObj) {
		moduleObj.context = dlg;
		moduleObj.closeDialog = dlg.close;
	}
	if (options.content) {
		dlg.ccayRender();
	}
	return dlg;
}
/**
 * @description 触发dialog的cancel按钮
 * @param {btn}
 *            cancel按钮： 内容
 */
Ccay.UI.dialog.triggerCancel = function(btn) {
	$(btn).parent().parent().children(':first').children(':first').click();
}

/**
 * @description MessageBox 提示弹出框控件接口
 * @param {String}
 *            content： 内容
 * @param {String}
 *            style： 内容(取值：success|error|warn|question)
 * @param {function}
 *            callback： 回调函数，点击确定执行
 * @param {boolean}
 *            hideClose： 是否隐藏关闭图标 默认显示
 * @param {boolean}
 *            encode： 是否支持html显示
 * @param {boolean}
 *            dialogOp： dialog 参数设置  
 */
Ccay.UI.showMessage = function(content, style, callback, hideClose, encode,dialogOp) {
	if(typeof content =="object"){
		style = content.style;
		callback = content.callback
		hideClose = content.hideClose;
		encode = content.encode;
		dialogOp = content.dialogOp;
		content = content.content;
	}
	var options = {
		width : 250,
		content : content,
		messageBox : {
			type : "message",
			style : style,
			encode : encode !== false
		},
		showCloseImg : !hideClose,
		fnClose : callback
	};
	$().dialog($.extend(options,dialogOp));
}

/**
 * @description MessageBox 确定框控件接口
 * @param {String}
 *            content： 内容
 * @param {function}
 *            callback(Boolean)： 点击确定事件
 */
Ccay.UI.confirm = function(content, callback, focusYes,isHtml , dialogOp) {
	var option = {
		width : 250,
		content : content,
		messageBox : {
			type : "confirm",
			focusYes : focusYes,
			encode : isHtml !== true
		},
		fnClose : function(dialog, op) {
			callback && callback(op.result); 
		}
	};
	$().dialog($.extend(option,dialogOp));
}
/**
 * @description tip 消息提示框
 * @param {String}
 *            content： 内容
 */
Ccay.UI.topBox = function(content, isHtml, autoClose, css, delay,style,dialogOp) {
	var op = {} , currLang = Ccay.Local.getCurrLanguage();
	if(typeof content =="object"){
		op = content;
		isHtml = content.isHtml;
		autoClose = content.autoClose;
		css = content.css;
		delay = content.delay;
		style = content.style;
		dialogOp = content.dialogOp;
		content = content.content;
	}
	if(content){
		content = isHtml !== true ? $i18n(content) : content;
		content = (op.encode !== false) ? content.encode() : content;
	}
	if(style){
		content = ("<div class='ccay-dialog-image image-{0}' style='margin:-12px 0px;'></div>"+content).formatValue(style);
	}else if(op.type){
		if(op.type == "big_sim"){
			content = '<div class="image-success-big" style="height:50px"></div><div class="content-big-sim"><h1>{0}</h1><div>&nbsp;</div></div>'
						.formatValue(content ? content : $i18n("ccay.workflow.message.submitSucess"));
		}else {
			var show_time = (currLang == "zh_CN") ? '<label id="time" class="count-down">3</label>  秒后自动跳转  或者   ' : 'You will be redirected in <label id="time" class="count-down">3</label> seconds,Or ';
			content = '<div class="image-success-big"></div><div class="content-big-com"><h1>{0}</h1><samp class="smallcontent">{1}</samp>'
						.formatValue( content? content : $i18n("ccay.workflow.message.submitSucessLong"),
							op.character ? $i18n(op.character) : "");
			content += '<samp>'+show_time+'</samp><samp class="jump-tip"><a class="big-top-jump">{0}</a></samp></div>'.formatValue($i18n("ccay.bigTopBox.forward.tip"));
		}
	}
	
	
	var topBox = $("#ccay_tip") , timer = Ccay.UI.Config.topBox.timer;
	
	if (topBox.length == 0 || ( topBox.attr("type") != op.type )) {
		if(topBox.length) $("#ccay_tip").remove();
		var options = {
	  		title : op.noTitle !== true ? (op.title || "ccay.common.message.msgtitle") : "",
			id : "ccay_tip",
			content : content,
			show : false,
			target : null,
			showHead : true,
			width : Ccay.UI.Config.topBox.width+50,
			modal : false,
			fixed : true,
			fnBeforeClose : function() {
				this.dom.hide();
				return false;
			}
		};
		if(op.type){
			options.width = options.width + 150;
			if(op.type == "big_sim"){
				options.height = 60;
				timer = 1000;
			}else if(op.type == "big_com"){
				options.height = 85;
				timer = 3000;
			}
		}
		var topBox = $().dialog($.extend(options,dialogOp)).removeClass("ccay-dialog");
	} else {
		topBox.manager().getBody().html(content);
	}
	css && ( typeof css == "object" ? topBox.css(css) : topBox.addClass(css));
	
	var win = $(window), leftWdith = $(Ccay.Config.Panel.leftPanel).width(),
		left = win.width() / 2 - topBox.width() / 2 + win.scrollLeft() + (leftWdith > 300 ? 0 : leftWdith) / 2, top = win.scrollTop() + Ccay.UI.Config.topBox.top;
    
	
	topBox.css({
				left : (dialogOp && dialogOp.left) ? dialogOp.left : left,
				top : (dialogOp && dialogOp.top) ? dialogOp.top : Ccay.UI.Config.topBox.top
			}).fadeIn(300);
			
	if(op.type){
		topBox.manager().getBody().css("text-align","center") && topBox.manager().getHead().css("border-bottom","none");
		if(op.type == "big_com" && currLang != "zh_CN"){
			topBox.manager().getBody().find(".smallcontent").css("width",topBox.width()*0.8+"px")
		}
	}
	topBox.attr("type",op.type ? op.type : "")
	
	var i=3 , interval;
	if (autoClose !== true){
		if(op.type && op.type == "big_com"){
			interval = setInterval(function(){
				i--;
				if(i==0){
					var bool = $("div.ccay-popup[type='big_com']:visible").length;
					clearInterval(interval);
					if(bool){
						topBox.hide();
						op.forwardUrl && Ccay.Page.forward(op.forwardUrl);
					}
				}
				$("#time").text(i);
			},1000)
		}else 
			topBox.delay(timer).fadeOut(delay || 300);
	}
	topBox.find(".big-top-jump").click(function(){
		clearInterval(interval);
		topBox.hide();
		op.forwardUrl && Ccay.Page.forward(op.forwardUrl);
	});
	return topBox;
};

/** 主区域Loading */
Ccay.UI.openMainLoading = function() {
	// Ccay.loading();
	Ccay.UI.loading(1);
}
/** 主区域Loading关闭 */
Ccay.UI.closeMainLoading = function() {
	// Ccay.loadingClose();
	Ccay.UI.loadingClose(1);
}


/** 全屏锁屏 */
Ccay.UI.bodyLoading = function(){
    var loading = $("#body_loding");
    if(!loading.length){
        loading = $('<span id="body_loding" class="loading" style="position:fixed"></span>').appendTo(document.body);
    }
    loading.show();
}
/** 关闭全屏锁屏 */
Ccay.UI.bodyLoadingClose = function(){
    $("#body_loding").hide();
}


/** loading方法 */
Ccay.UI.loading = function(locked) {
	// lock 为true 的时候，为 全局loading，会遮盖住loading区域不让操作
	if (locked) {

		var loadPanel = $('div.ccay-dialog').not(".message-box,#ccay_infoTip"), isGlobal = 1;

		if (!loadPanel.length) {

			loadPanel = $(Ccay.Config.Panel.globalLoading);

		} else if (loadPanel.css('display') == 'none') {

			isGlobal = 0;
		}
		return loadPanel.loading(isGlobal);
	} else {
		// 一个小的弹出loading框，不会影响用户操作
		var loading = $('#loading_msg');
		if (loading.length == 0) {
			$().dialog({
						title : $i18n(Ccay.UI.Config.loading.title),
						id : "loading_msg",
						target : null, 
						showHead : false,
						content : $i18n(Ccay.UI.Config.loading.content),
						modal : false,
						drag : false,
						show : false,
						width : Ccay.UI.Config.loading.width,
						fnBeforeClose : function() {
							this.dom.hide();
							return false;
						}
					}).removeClass("ccay-dialog");

			loading = $('#loading_msg').hide();
		}

		var win = $(window), leftWdith = $(Ccay.Config.Panel.leftPanel).width(), left = win.width() / 2 - loading.width() / 2 + win.scrollLeft() + (leftWdith > 300 ? 0 : leftWdith) / 2, top = win.scrollTop() + Ccay.UI.Config.loading.top;

		return loading.css({
					top : top,
					left : left,
					width : Ccay.UI.Config.loading.width,
					position : 'absolute'
				}).show();

	}
}
/** 重写系统loading方法 */
Ccay.UI.loadingClose = function(locked) {
	if (locked) {
		var loadPanel = $('div.ccay-dialog:last');
		if (!loadPanel.length)
			loadPanel = $('#' + Ccay.Config.Panel.centent);

		loadPanel.loadingClose();
	} else if (Ccay.Core_ajaxCount["get"] <= 0) {
		$('#loading_msg').hide();
	}
}

/**
 * 根据参数生成按钮html代码
 * 
 * @param {string}
 *            text 国际化资源key
 * @param {string}
 *            click 绑定的事件字符串
 * @param {string}
 *            permission 绑定的权限点，如过有权限才生成该代码，否则返回空字符串
 * @param {string}
 *            btntype 是否是图片按钮;'input','img','link'三种，默认为input
 * @param {string}
 *            type 图片按钮类型
 * @return {string} 生成的html源码
 */
Ccay.UI.button = function(text, click, permission, type, imgtype, isI18n, attr) {
	// 只传一个对象参数时,参数处理
	if ($.isPlainObject(text)) {
		var op = text,
			text = op.text,
			click = op.click,
			permission = op.permission,
			type = op.type,
			imgtype = op.imgtype,
			isI18n = op.isI18n,
			attr = op.attr,
			css = op.css || "";
			//jmlHtmlProp = op.jmlHtmlProp;
	}
	click = click ?  'onclick="{0}"'.formatValue(click) : "";
	if (permission && !Ccay.Permission.check(permission))
		return "";
	if (attr == void 0)
		attr = "";
	if (isI18n !== false)
		text = $i18n(text);

	var tmpl = Ccay.UI.Config.button;
	var prop = "";
	if (attr && typeof attr == "object") {
		for (var k in attr) {
			prop += k + "=\"" + attr[k] + "\" ";
		};
	};
	attr = (prop || attr);
	switch (type) {
		case "img" :
			return tmpl.img.formatText(imgtype, click, text, attr, css);
		case "link" :
			return tmpl.link.formatText(click, encode(text), attr, css);
		case "imgBtn" :
			return tmpl.imgBtn.formatText(imgtype, click, encode(text), attr, css);// 利用attr可传入按钮的id
		default :
			css && (attr += ' class="{0}"'.formatValue(css));
			return tmpl.input.formatText(text, click, attr);
	}
};

/**
 * 根据参数生成按钮html代码
 * 
 * @param {}
 *            op
 * @param {}
 *            isEncode
 * @return {String}
 */
Ccay.UI.newButton = function(op, isEncode) {
	// 判断权限
	if (op.permission && !Ccay.Permission.check(op.permission)) {
		return "";
	};
	// id设置处理
	if(op.id){
		if(op.attr)
			op.attr.id = op.id;
		else
			op.attr = {id:op.id};
	};
	// attr处理 拼接字符串
	op.prop = "";
	if (op.attr){
		var tempStr = [];
		$.each(op.attr, function(i, n) {
					if (n != "") {
						tempStr.push(i + "='" + n + "' ");
					}
				});
		op.prop = tempStr.join("");
	};
	// 国际化
	op.text = $i18n(op.text);
	// 是否编码
	if (isEncode != false) {
		op.text = encode(op.text);
	};
	var tmpl = Ccay.UI.Config.newButton[op.type] || Ccay.UI.Config.newButton["input"];

	return tmpl.formatField(op);
};

/**
 * 批零生成button的html字符串
 * 
 * @param {}
 *            btns
 * @return {}
 */
Ccay.UI.buttonBuilder = function(btns) {
	var html = [];
	for (var i = 0; i < btns.length; i++) {
		html.push(Ccay.UI.newButton(btns[i]));
	}
	return html.join("");
};

Ccay.UI.showImage = function(caller, showSource) {
	
	caller = $(caller);

	var title = caller.attr('alt') || caller.attr('title'), src = caller.attr('src') || caller.attr('img') , openWay = caller.attr('openWay') || "";

	var imgPanel = $('#show_image');
	if (!imgPanel.length) {
		var sbHtml = new Ccay.StringBuilder();
		
		if(openWay && openWay === "lock"){
			sbHtml.append('<div class="ccay-overlay" id="ccay_dialog_overlay_img" style="display: block; z-index: 999;"></div>');
		}
		
		sbHtml.append("<div id='show_image' class='loading ccay-image-show'>").append("<div class='ccay-image-head'><span>").append($i18n(title)).append("</span>");
		
		
		if(showSource != false){
			sbHtml.append("<a class='ccay-image-view' target='_blank' title='view source' href='").append(src).append("'></a>");
		}
		sbHtml.append("<a class='ccay-image-close' title='close'></a></div>").append("<div class='ccay-image-body'><img onload='Ccay.UI.autoImage(this,true);$(this).parent().parent().show()' src='").append(src).append("' /></div></div>");

		
		Ccay.Page.getContentPanel().append(sbHtml.toString());
		$("a.ccay-image-view").attr("title",$i18n('ccay.workflow.message.viewSource'));
		$("a.ccay-image-close").attr("title",$i18n('ccay.workflow.message.close'));


		// caller.after(sbHtml.toString());
		var win = $(window);
		imgPanel = $('#show_image').css("top", win.scrollTop() + 200).css("overflow","auto");
		imgPanel.find('a.ccay-image-close').click(function() {
					$('#show_image').hide();
					openWay === "lock" && $("#ccay_dialog_overlay_img").hide();
				});
		/*
		 * imgPanel.find('img').bind("keydown",function(e){ e.keyCode == 27 &&
		 * $('#show_image').hide(); });
		 */
	} else {
		openWay === "lock" && $("#ccay_dialog_overlay_img").show();
		var img = imgPanel.find('img'), imgSrc = img.attr('src');
		if (src != imgSrc) {
			//修复图片导出不一致问题。
			imgPanel.find(".ccay-image-view").attr("href",src);
			img.attr("src", "").attr('src', src);
			imgPanel.height("auto").width("auto").loadingClose();
			imgPanel.children(".ccay-image-head").children("span").text($i18n(title));
		}else{
			imgPanel.show();
		}
		
	}
};

Ccay.UI.autoImage = function(img, showmax) {
	img = $(img).css('visibility', 'visible');
	var width = img.width();
	if (width) {
		var win = $(window), winWidth = win.width();
		if (!showmax) {
			var maxWidth = winWidth * 0.8, maxHeight = win.height() * 0.8 - 100;

			if (width > maxWidth) {
				width = maxWidth;
				img.width(width);
			}
			var height = img.height();
			if (height > maxHeight) {
				img.width('').height(maxHeight);
				width = img.width();
			}
		}
		var left = winWidth / 2 - width / 2 + win.scrollLeft(), top = win.scrollTop() + 100;
		var panel = img.parent().parent().height('auto').css({
					top : top > 0 ? top : 0,
					left : left > 0 ? left : 0,
					width : width
				}).removeClass("loading");
		if ($.browser.msie && $.browser.version == 6)
			panel.children(':first').width(width);
		
	}
};

Ccay.UI.clearValidError = function() {
	$("label.error").hide();
};

$.fn.ccayCombobox = function(conf) {
	this.each(function(i) {
				var field = $(this);
				if (field.attr("init")) {
					return;
				}
				field.attr("init", true);
				var container = field.attr("ingrid");
				if (container) {
					container = $("#" + container);
				}
				var appendAfter = container ? false : true;

				var valueField = field.attr("valueField") || "value", displayField = field.attr("displayField") || "text";
				var dsconfig = field.attr("service").split(":");
				var multi = field.attr("multi") == "true";
				var emptyText = field.attr("emptyText");
				var connector = field.attr("connector");
				var combo = field.attr("combo") !== "false", initInput = field.attr("initInput") !== "false";
				var fnChange = field.attr("fnChange") ? Ccay.Core.Namespace.getVariable(field.attr("fnChange")) : "";
				var dsType = dsconfig[0];
				var historySupport = field.attr("historySupport") ? field.attr("historySupport")!== "false" : field.attr("historySupport");
				var settings = $.extend({}, {
							container : container,
							emptyText : emptyText,
							multi : multi,
							initInput : initInput,
							fnChange : fnChange,
							combo : combo,
							connector : connector,
							valueField : valueField,
							displayField : displayField,
							historyKey : field.attr("service"),
							historySupport:historySupport
							
						}, conf, field.getConfig());
				var ds = dsconfig[1];
				!settings.multiDisabled && settings.multi && field.attr("readonly","readonly");
				if (dsType == "ENUM") {
					settings.valueField = "value";
					settings.displayField = "displayValue";
				}
				//兼容jml
				if(conf && conf.dataset){
					if(dsType === "SYNC"){
						//debugger;
						var syncFn = conf.dataset;
						settings.ajax = {
							url : "",
							beforeRequest : function(ajax, caller, list) {
								syncFn(ajax.success, caller);
								return false;
							}
						};
						//去除dataset属性，否则不会发送请求
						delete settings.dataset;
					}else{
						settings.dataset = conf.dataset;
						if(typeof settings.dataset =="function"){
							settings.dataset = settings.dataset();
						}
					}
				}else{
					if (dsType === "REST") {
						settings.ajax = {
							url : ds
						};
					} else if (dsType === "SYNC") {
						var fn = Ccay.Core.Namespace.getVariable(ds);
						settings.ajax = {
							url : "",
							beforeRequest : function(ajax, caller, list) {
								fn(ajax.success, caller);
								return false;
							}
						};
					} else {
						settings.dataset = Ccay.UI.getStaticData({
										service : field.attr("service"),
										supportLang : field.attr("supportLang")
									});
					}
				}
				field.dropdown(settings);
			});
	return this;
};

Ccay.UI.getStaticData = function(format) {
	var service = format.service;
	if (service) {
		if (typeof(service) == "string") {
			if (service.indexOf(":") > 0) {
				var dsconfig = service.split(":"), dsType = dsconfig[0], ds = dsconfig[1].replace(/(^\s*)/, "");
				if (dsType === "FN"){
					return Ccay.DataHelper.getObj(ds)();
				}else if(dsType === "ENUM"){
					return Ccay.Component.Enum.getList(ds,format.supportLang);
				}
			} else
				return Ccay.DataHelper.getObj(service);
		} else
			return service;
	}
	return null;
}

/**
 * @description 初始化Ldap标签$(".id_ldap"）
 * @return {JqDom} 对象本身
 */
$.fn.ccayLdap = function(conf) {
	conf = conf || {};
	this.each(function(index, element) {
				var field = $(this);
				// 如果已经初始化过，则不做操作
				if (field.attr("init")) {
					return;
				}
				field.attr("init", true);

				var valueField = field.attr("valueField") || "userId", asyncCreate = field.attr("asyncCreate") == "true";
				var templ = "<tr class='{0} ldap-suggest  ${&data._history}' val='${&" + valueField + "}' dept='${&dept}' userid=${&userId} userAccount=${&userAccount} userCN='${&userCN}'><td><span><font class='list-text'>${userCN}</font>(${userAccount})</span></td><td><span class=ldap_dept_span>${dept}</span></td></tr>"
				var isMulti = field.attr("multi") == "true";
				var islocalUser = field.attr("localUser") == "true";
				//多人员联想框是否排序
				var sortBy,getTextAjaxUrl="services/ccay/security/user/list/byids";
				if(isMulti && field.attr("sortBy") && (jQuery.inArray(field.attr("sortBy"),["userAccount","userCN"]) != -1)){
					sortBy = field.attr("sortBy");
				}
				// 用户联想框配置项目
				var config = $.extend({
							valueField : valueField,
							sortBy : sortBy,
							displayField : "userCN",
							defaultFilter : "%",
							multi : isMulti,
							delay : 1000,
							cacheReqest : null,
							showTrigger : false,
							initInput : true,
							multiSplit : ", ",// 多选分隔符号
							fnBeforeSelected : function(value, text, item, selector, users) {
								if (item && (!users || !users.creationDate)) {
									var oldUserId = users.userId;
									var restPath = "services/ccay/security/user/single/{0}".formatURI(item.attr("userAccount"));
									var ops = {
										url : restPath,
										async : asyncCreate,
										success : function(data) {
											//切换工号处理
											if(valueField=="userId" && value.indexOf(data.userId) == -1){
												 value = value.replace(oldUserId,data.userId);
												 setTimeout(function(){
													 field.dataValue(value);
												 },0)
											}
											
										},
										error : function() {
											return true
										}
									}
									Ccay.doGet(ops);
								} else if ($.isArray(users)) {
									var accounts = [],oldIds={};
									for (var i = 0; i < users.length; i++) {
										if (!users[i].creationDate) {
											accounts.push(users[i].userAccount);
											oldIds[users[i].userAccount] = users[i].userId;
										}
									}
									if (accounts.length > 0)
										Ccay.doPost({url:"services/ccay/security/user/create/w3Account", 
											async: asyncCreate,
											data: accounts, 
											success: function(datas) {
											var ischange = false;
											if(valueField =="userId"){
												$.each(datas,function(data){
													var user = this,oldid = oldIds[user.userAccount];
													if(oldid !== user.userId){
														ischange = true;
														value = value.replace(oldid,data.userId);
													} 
												})
												ischange &&  setTimeout(function(){
													 field.dataValue(value);
												 },0)
											}
										 }
										});
								}
							},
							fnBinded : function(list, datas) {
								// 调整head 让它与内容列对齐
								var bodyHeight = list.find(".suggest_body_div table").height();
								if (bodyHeight < 160) {
									list.find(".suggest_body_div").height(bodyHeight);
								}
							},
							panelBegin : "<div class=suggest_body_div  style='overflow:visible' ><table class=list><tbody>",
							panelEnd : "</tbody></table></div>",
							item : templ,// 构建模板
							suggestLength : 4,// 输入四个字符才开始联想
							ajax : {
								url : islocalUser? "services/ccay/security/user/local/page/100/1/{0}" : "services/ccay/security/user/suggest/{0}",
								error : function() {
									return true
								}
							},
							getTextAjax : {
								url : "services/ccay/security/user/list/byids",
								error : function() {
									return true;
								}
							}
						}, conf, field.getConfig());
				// 如果是用户帐号保存，则通过帐号反查询
				if (valueField == "userAccount") {
					config.historyKey = "ldap_useraccount";
					config.getTextAjax.url = "services/ccay/security/user/list/byaccounts";
				}else if(valueField == "employeeNumber"){
					config.getTextAjax.url = "services/ccay/security/user/list/byemployee";
				}
				// gt_grid 特殊处理
				var container = field.attr("ingrid");
				if (container) {
					config.nopending = true;
					config.container = $("#" + container);
					config.appendAfter = false;
				}
				field.suggestion(config);
				field.removeClass("ccay-suggest");
			});
	return this;
};
$.validator.addMethod("ccay-user", function(value, element) { 
	var manager =  $(element).manager();
	return manager.valid ? manager.valid() : true;
});

// ----------------- Suggest ---------------------
/**
 * @description 初始化Suggest标签 $("input:text.ccay-suggest")
 * @return {JqDom} 对象本身
 */
$.fn.ccaySuggest = function(conf) {
	// 如果已经初始化过，则不做操作
	try {
		if (this.attr("init")) {
			return;
		}
		
		//是否设置提示
		if(conf.placeholder){
			this.attr("placeholder",$i18n(conf.placeholder));
			if(!('placeholder' in document.createElement('input'))){
				this.addClass("filter-gray").val($i18n(conf.placeholder));
				this.addClass("placeholder");
				this.attr("search","")
			}
		}
		
		// 标记已经初始化过
		this.attr("init", true);
		this.addClass("ccay-suggest");
		var config = $.extend({
					valueField : "name",
					displayField : "name",
					defaultFilter : "%",
					panelBegin : "",
					panelEnd : "</tbody></table>",
					// item:templ,
					ajax : {
						url : conf.url,
						setAjax : function(ajax, ui) {
							var param = conf.queryParam || conf.queryParams;
							if (typeof param == "function") {
								param = param(ajax.data);// 如果该参数是一个方法，这通过这个方法得到查询参数并设置到
															// param中
							}
							// 如果param不为空，则让他与ajax的参数data合并
							if (param) {
								ajax.data = $.extend(ajax.data || {}, param);
							}
						}
					},
					fnBinded : function(selector, datas) {
						// 调整head 让它与内容列对齐
						var headTds = selector.find("div.ccay-suggest-head table thead tr:first td");
						var bodyTds = selector.find("div.ccay-suggest-body table tbody tr:first td");
						if (headTds.length > 0) {
							bodyTds.each(function(index) {
										if (index < bodyTds.length - 1) {
											var head = $(headTds[index]);
											if (head.children("span").width() < $(this).width()) {
												head.width($(this).width());
											}
										}
									});
						}
					}
				}, conf, this.getConfig());
		// 构建显示样式 模板
		var fieldMapper = conf.fieldMapper;
		// 根据配置 构建数据项模板的td 与 构建表头的td
		var colBody = [], colHead = [];
		if(conf.suggestMulti){
		    colHead.push("<td class='suggestSelectAll'><span></span></td>");
		}
		var showFieldCount = 0;
		if(fieldMapper){
			for (var attr in fieldMapper) {
				if (attr == config.displayField) {
					if(conf.suggestMulti){
					    colBody.push("<td class='suggestSelect suggest-multi-noSelect'><span></span></td>");
				    }
					colBody.push('<td><span><font class="list-text ccay-suggest-font"  title = "${&{2}}" >${{2}}</font></span></td>');
				} else {
					colBody.push('<td ><span><font class="ccay-suggest-font" title="${&' + attr + '}">${' + attr + '}</font></span></td>');
				}
				// field 计数器
				showFieldCount++;
				colHead.push("<td><span><font>" + fieldMapper[attr] + "</font></span></td>");
			}
		// 2014.2.17 添加不指定列的情况，默认显示displayField，值为valueField。 l00195395 
		}else{
			colBody.push('<td><span><font class="list-text ccay-suggest-font"  title = "${&{2}}" >${{2}}</font></span></td>');
			showFieldCount = 1;
			//colHead.push("<td><span><font>" + config.displayField + "</font></span></td>");
		}
		// 数据项模板
		var templ = '<tr  class="{0} ${&data._history}" val="${&{1}}">' + colBody.join("") + '</tr>';
		// 如果只显示一列，则无需现在列宽
		if (showFieldCount == 1) {
			templ = templ.replace("ccay-suggest-font", "");
		}
		// 如果表头只有一个，则不显示表头，直接将headDiv赋值为空，否则使用生产的表头代码
		var headDiv = showFieldCount > 1 ? "<table><thead><tr>" + colHead.join("") + "</tr></thead></table>" : "";
		var bodyDiv = templ + "</tbody></table>";

		// 表头模板
		var begin = "<table class=list><tbody>"
		config.panelBegin = begin;
		config.fnBuildSelector = function(div, datas) {
			div.find("div.ccay-selector-head").addClass("ccay-suggest-head").html(headDiv);
			div.find("div.ccay-selector-body").addClass("ccay-suggest-body");
			conf.fnBuildSelector && conf.fnBuildSelector(div, datas);
		}
		config.item = templ;
		// gt_grid 特殊处理
		var container = this.attr("ingrid");
		if (container) {
			config.nopending = true;
			config.container = $("#" + container);
			config.appendAfter = false;
		}
		this.suggestion(config);

	} catch (e) {
		Ccay.Core.log("联想框 suggest 配置错误，控件 name:" + this.prop("name") + ", errMsg:" + e.message);
	}

};


//非IE浏览器自适应高度绑定函数
 Ccay.UI.txtChange = function(e) {
	var textarea = $.getEventTarget(e), maxHeight = (textarea.attr("maxheight") * 1 || 500);
	var scrollHeight = textarea[0].scrollHeight * 1;
	if (maxHeight > textarea[0].scrollHeight * 1) {
		textarea.css("height", textarea[0].scrollHeight + "px");
	} else {
		textarea.css("overflow-y", 'auto');
	}
};
// IE textarea自适应高度绑定函数
Ccay.UI.ieTxtChange=function(e) {
	// getEventTarget方法

	var textarea = $.getEventTarget(e);
	var maxheight = textarea.attr("maxheight");
	var maxHeight = (maxheight * 1 || 500);
	var scrollHeight = textarea[0].scrollHeight * 1;
	var height = textarea[0].style.height;
	height = height.substring(0, height.indexOf("p"));
	setTimeout(function() {
				// 判断
				if (maxHeight > scrollHeight) {
					
					if (scrollHeight > height || scrollHeight == height) {
						textarea.css("height", scrollHeight + "px");
					}
				} else {
				textarea.css("overflow-y", 'auto');
				}
			}, 0);
};
$.fn.ccayTextarea = function() {
	// each 判断
	if (this.attr("init")) {
		return;
	}
	this.attr("init", true);
	//FIXMI IS IE?
//	if ($.browser.msie) {
//		this.bind("paste keyup", Ccay.UI.ieTxtChange);
//	} else {
//		this.bind("input", Ccay.UI.txtChange);
//	}
	this.bind("input", Ccay.UI.txtChange);
};

$.fn.ccayRender = function() {
	Ccay.UI.init(this);
};
Ccay.UI.init = function(context) {
	context = context || window.document.body;
	context = context.jquery ? context : $(context);
	context.find(".hasPermission[ccayPermission]").ccayHasPermission();
	context.find(".noPermission[ccayPermission]").ccayNoPermission();
	var controls = $(".init,.i18n", context);
	controls.filter(".i18n").ccayI18n();
	controls.filter("form").each(function() {
				var form = $(this);
				form.ccayValidate(form.getConfig()).submit(function() {
							return false;
						})
			});
	var comboList = controls.filter("input.ccay-combobox");
	var codes = [],list = [],langCodes = [],langList = [];
	comboList.each(function() {
		var service = $(this).attr("service") || "";
		var dsconfig = service.split(":"), dsType = dsconfig[0], ds = dsconfig[1];
		if (dsType == "LOOKUP3" && !$(this).attr("init")) {
			if($(this).attr("supportLang") === "true" || $(this).attr("supportLang") === undefined){
				langCodes.push(ds);
				langList.push(this);
			}else{
				codes.push(ds);	
				list.push(this);
			}
		}else{
			$(this).ccayCombobox();
		}
	});
	//LOOKUP3合并请求
	if(list.length){
		var datas = Ccay.UI.getStaticData({
			service : "LOOKUP3:"+codes.join(",")
		});
		$.each(list,function(i,d){
			var service = $(this).attr("service") || "";
			var dsconfig = service.split(":"), dsType = dsconfig[0], ds = dsconfig[1];
			$(this).ccayCombobox({
				dataset:datas.length ? datas : (datas[ds]||[])
			});
		});
	}
	//LOOKUP3根据当前语言合并请求
	if(langList.length){
		var datas = Ccay.UI.getStaticData({
			service : "LOOKUP3:"+langCodes.join(","),
			supportLang:true,
		});
		$.each(langList,function(i,d){
			var service = $(this).attr("service") || "";
			var dsconfig = service.split(":"), dsType = dsconfig[0], ds = dsconfig[1];
			$(this).ccayCombobox({
				dataset:datas && datas.length ? datas : (datas[ds]||[])
			});
		});
	}
	controls.filter(".ccay-user").ccayLdap();
	controls.filter(".PersonInfo").ccayUserInfo();
	controls.filter(".GroupInfo").ccayGroupInfo();
	controls.filter(".ccay-menubutton.init").ccayMenuButton();
	controls.filter(".ccay-autosize").ccayTextarea();
	Ccay.UI.initFormContent(context);
	Ccay.UI.Renders.fire(controls, context);
};

Ccay.UI.initFormContent = function(context) {
	Ccay.UI.InitForm(context.find("form"));
}
Ccay.UI.InitForm = function(form){
	form.find(":reset,.ccay-operate .ccay-button.reset,.ccay-toolbar .ccay-button.reset").click(function() {
				var btnReset = $(this), form = btnReset.parents('form');
				form.ccayReset();
				return false;
			});
	//form中的ccay-operate,ccay-toolbar里的.ccay-button.reset，重置form事件
//	$(".ccay-button.reset",form.find(".ccay-operate,.ccay-toolbar")).click(function() {
//				var btnReset = $(this), form = btnReset.parents('form');
//				form.ccayReset();
//				return false;
//			});
	form.keydown(function(e) {
				if (e.keyCode == 13) {
					var target = $.getEventTarget(e), type = target.attr('type');
					if (type != "reset" && type != "button") {
						var btn = $(this).find(":button.default:first");
						if (btn.length) {
							e.stopPropagation();
							btn.click();
						}
						var defaultSpan = $(this).find(".ccay-button.default:first");
						if (defaultSpan.length) {
							e.stopPropagation();
							defaultSpan.click();
						}
					}

				}
			})
	form.filter('.longtitle').find('samp').each(function() {
				var title = $(this), text = title.text().trim();
				if (text.replace(/[^x00-xff]/g, "**").length > 20)
					title.attr('title', text);
			});
			
	//textarea 字数限制处理
	var textareas = form.find(".ccay-form-whole textarea[textarea-maxlength]").css("height","80px") ,
		curContent = Ccay.Local.getCurrLanguage() == "zh_CN" ? "<span>还可以输入</span><span class='only-count'>1</span><span>字</span>" : "<span class='only-count'>1</span><span>characters remained</span>"
		curr_div = "<div class='textarea-maxlength'>"+curContent+"</div>";
	if(textareas.length){
		var parent = textareas.parent() , textarea , maxlength_div;
		parent.append(curr_div).css("height","109px");
		parent.prev("samp").css("height","109px");
		
		$.each(textareas,function(i,j){
			textarea = $(j);
			maxlength_div = textarea.next(".textarea-maxlength");
			maxlength_div.find("span.only-count").text(textarea.attr("textarea-maxlength"));
		});
		textareas.on("keypress", function(e) {
			   var c = e.keyCode, input = $(this), value = input.val(), maxlength = input
			     .attr("textarea-maxlength"),selectText = 0;
			   // 当为最大的时候 选中字符可以进行修改
			    if(value.trim().length >= maxlength){
			     if (document.selection) { //for IE
			      selectText = document.selection.createRange().text.length;
			      } else if (this.selectionStart || this.selectionStart === 0) {
			       selectText = this.selectionEnd - this.selectionStart;
			      }
			     if(selectText){
			      setTimeout(function() {
			       if (value.trim().length > maxlength) {
			        input.val(value.substr(0, maxlength));
			       }
			      }, 10);
			      }else{
			       e.preventDefault();
			             return;
			      }
			     
			        }
			   
			    
			  }).on("keyup",function(){
				   var input = $(this), value = input.val(), maxlength = input.attr("textarea-maxlength");
				   var only_count = $(this).attr("textarea-maxlength") - $(this).val().trim().length;
				    input.val(value.substring(0, maxlength));
				   $(this).next(".textarea-maxlength").find("span.only-count")
				     .text(only_count < 0 ? 0 : only_count);
				  });
		
		if(navigator.userAgent.toLowerCase().match(/(msie\s|trident.*rv:)([\d.]+)/) && $.browser.version < 9){
			  textareas.on("select", function(e) {
				  var input = $(this), value = input.val(), maxlength = input
				     .attr("textarea-maxlength");
				   if (value.trim().length > maxlength) {
				    input.val(value.substring(0, maxlength))
				   }
				   var only_count = maxlength - input.val().trim().length;;
				   input.next(".textarea-maxlength").find("span.only-count")
				     .text(only_count < 0 ? 0 : only_count);
				  });
		}else{
			textareas.on("input", function(e) {
				var input = $(this), value = input.val(), maxlength = input
						.attr("textarea-maxlength");
						if(value.trim().length > maxlength){
					input.val(value.substring(0, maxlength))
						}
						var only_count = maxlength - input.val().trim().length;;
				input.next(".textarea-maxlength").find("span.only-count")
						.text(only_count < 0 ? 0 : only_count);
			});
		}
	}
	
	//无表格线样式处理
	if(workspaceVO.themeName != "default" && form.hasClass("ccay-form")){
		form.each(function(){
			var panel = $(this),children = panel.children();
			if(children.length == 0 
				|| children.filter('.ccay-form-content,.ccay-table').length > 0
				|| panel.find('.ccay-form-body:first,.ccay-form-custom:first').length == 0)
				return;

			//将form录入内容放入到content容器中
			var operation = children.filter('.ccay-operate'),content = $.create('div','ccay-form-content');
			if(operation.length){
				//把ccay-operate之上的放入content中
				var item;
				children.each(function(){
					item = $(this);
					if(item.hasClass('ccay-operate'))
						return false;
					item.appendTo(content);
				})
			}else{
				content.append(children);
			}
			content.prependTo(panel);
		})
		
	}
}